package imaa.escola.turma.repository;

import imaa.escola.disciplina.datatransfer.DisciplinaDto;
import imaa.escola.disciplina.repository.DisciplinaRepository;
import imaa.escola.professor.datatransfer.ProfessorDto;
import imaa.escola.professor.repository.ProfessorRepository;
import imaa.escola.turma.datatransfer.PesquisaTurmaDto;
import imaa.escola.turma.datatransfer.TurmaDto;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

public class TurmaRepositoryImpl implements TurmaRepositoryCustom {

	@Autowired
	private TurmaRepository turmaRepository;
	
	@Autowired
	private DisciplinaRepository disciplinaRepository;
	
	@Autowired
	private ProfessorRepository professorRepository;

	@Autowired
	private JdbcTemplate template;

	@SuppressWarnings("rawtypes")
	public List<TurmaDto> findByExample(PesquisaTurmaDto dto) {
		String sql = "SELECT * FROM turma WHERE 1=1 ";
		if (dto.descricao != null)
			sql += "AND LOWER(DSC_TURMA) LIKE LOWER('%" + dto.descricao
					+ "%') ";
		if (dto.idDisciplina != null)
			sql += "AND SEQ_DISCIPLINA = " + dto.idDisciplina + " ";
		if (dto.idProfessor != null)
			sql += "AND SEQ_PESSOA_PROFESSOR= " + dto.idProfessor + " ";
		List<TurmaDto> lista = new ArrayList<TurmaDto>();
		List<Map<String, Object>> rows = template.queryForList(sql);

		for (Map row : rows) {
			TurmaDto turma = new TurmaDto();
			turma.id = Long.parseLong(String.valueOf(row.get("SEQ_TURMA")));
			turma.descricao = (String) (row.get("DSC_TURMA"));
			Long idDisciplina = Long.parseLong(String.valueOf(row.get("SEQ_DISCIPLINA")));
			turma.disciplina = new DisciplinaDto(disciplinaRepository.findOne(idDisciplina));
			Long idProfessor = Long.parseLong(String.valueOf(row.get("SEQ_PESSOA_PROFESSOR")));
			turma.professor = new ProfessorDto(professorRepository.findOne(idProfessor));

			lista.add(turma);
		}
		return lista;
	}


	
	}


